﻿namespace EasyGo.Logic.Managers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using EasyGo.Common;
    using EasyGo.Common.Commands;
    using EasyGo.Logic.Model;

    public class ProjectManager : IProjectManager
    {
        private readonly IRepository<Project> projectRepository;

        public ProjectManager(IRepository<Project> projectRepository)
        {
            this.projectRepository = projectRepository;
        }

        public void CreateProject(EditProjectCommand command)
        {
            command.Validate();
            var project = new Project();
            project.CustomerId = command.CustomerId;
            project.Name = command.Name;
            project.Deadline = command.Deadline;
            project.Description = command.Description;
            project.AddDate = DateTime.Now;
            Transaction.Execute(() => this.projectRepository.Create(project));
        }

        public void EditProject(EditProjectCommand command)
        {
            command.Validate();
            Transaction.Execute(
                () =>
                    {
                        var toEdit = this.projectRepository.Load(command.Id);
                        if (toEdit != null)
                        {
                            toEdit.CustomerId = command.CustomerId;
                            toEdit.Deadline = command.Deadline;
                            toEdit.Description = command.Description;
                            toEdit.Name = command.Name;
                            this.projectRepository.Update(toEdit);
                        }
                    });
        }

        public void DeleteProject(int projectId)
        {
            Transaction.Execute(() =>
            {
                var toDelete = this.projectRepository.Load(projectId);
                this.projectRepository.Delete(toDelete);
                this.projectRepository.SaveChanges();
            });
        }
    }
}
